import router from './router'
import store from './store'
import { Message } from 'element-ui'
import { getToken } from '@/utils/auth' // 验权

function hasPermission(roles, permissionRoles) {
  if (roles.indexOf('all') >= 0) return true
  if (!permissionRoles) return true
  return roles.some(role => permissionRoles.indexOf(role) >= 0)
}

const whiteList = ['/login'] // 不重定向白名单
router.beforeEach((to, from, next) => {
  if (getToken()) {
    if (store.getters.roles.length === 0) {
      store.dispatch('GetInfo').then(res => { // 拉取用户信息
        const roles = res
        store.dispatch('GenerateRoutes', { roles }).then(() => {
          router.addRoutes(store.getters.addRouters)
          next({ ...to, replace: true })
        })
      }).catch((err) => {
        Message.error(err || '验证失败 请重新登录')
        store.dispatch('LogOut').then(() => {
          next({ path: '/login' })
        })
      })
    } else {
      // 没有动态改变权限的需求可直接next() 删除下方权限判断 ↓
      // if (hasPermission(store.getters.roles, to.meta.authKey)) {
      next()//
      // } else {
      // next({
      // path: '/401',
      // replace: true,
      // query: { noGoBack: true }
      // })
      // }
    }
  } else {
    if (whiteList.indexOf(to.path) !== -1) {
      next()
    } else {
      next('/login')
    }
  }
})
